import {
  Cart
} from 'cart-model.js';
import {
  Product
} from '../product/product-model.js';
var cart = new Cart(); //实例化 购物车
var product = new Product();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectedCounts: 0, //总的商品数
    selectedTypeCounts: 0, //总的商品类型数
    lasttime: 0,
    loaded:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(options) {
    this._loadData();
  },

  /*加载所有数据*/
  _loadData: function() {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    cart.getCartData((data) => {
      
      if(data.errcode=='401'){
        that._loadData();
      }
      var itemList = data.items;
      //声明一个空的数组
      var items = [];
      var able = [];
      //遍历数据
      for (let i in itemList) {
        //检查购物车有下架并且已选择的商品，然后重新选择
        for (let j in itemList[i].data){
          if (itemList[i].data[j].skusStatus.status != -1 && itemList[i].data[j].selected == 1){
            able.push(parseInt(itemList[i].data[j].id))
          }
          if (itemList[i].data[j].skusStatus.status == -1){
            itemList[i].data[j].selected == 0
          }
        }
        //push到空数组里
        items.push(itemList[i]);
      }
      if(able){
        cart.getcalculatorTototal(able, (data) => {
          wx.hideLoading();
        });
      }else{
        wx.hideLoading();
      }
      var cartData = data.items = items;
      if (cartData) {
        cartData = that._isShopSelected(cartData);
        that.setData({
          cartData: cartData,
          total: data.sale_real_total,
          loaded : true
        });
      }

    });
  },

  /*勾选更新总价*/
  _resetCalculatorTotoltal: function(ids = Array()) {
    var cartData = this._isShopSelected(this.data.cartData);
    var selectedIds = this._getSelectedGoods();
    cart.getcalculatorTototal(selectedIds, (data) => {
      if (data.status == 1) {
        this.setData({
          cartData: cartData,
          total: data.total,
        })
      }

    });
  },

  // 数量调整更新总价
  _countTotoltal: function(id, mark) {
    cart.getChangeCounts(id, mark, (data) => {
      if (data.status == 1) {
        this._resetCalculatorTotoltal();
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },

  /*调整商品数目*/
  changeCounts: function(event) {
    var id = cart.getDataSet(event, 'id'),
      mark = cart.getDataSet(event, 'type'),
      shopIdx = this._getProductIndexById(id).i,
      index = this._getProductIndexById(id).j;
    var num = product.changeCounts(event, this.data.cartData[shopIdx].data[index].num);
    cart.getChangeCounts(id, mark, (data) => {

      if (data.status == 1) {
        this.data.cartData[shopIdx].data[index].num = num;
        this.setData({
          cartData: this.data.cartData
        })
        this._resetCalculatorTotoltal();
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });

  },

  /*根据商品id得到 商品所在下标*/
  _getProductIndexById: function(id) {
    var cartData = this.data.cartData,
      len = cartData.length;
    for (let i = 0; i < len; i++) {
      var childlen = cartData[i].data.length;
      for (let j = 0; j < childlen; j++) {
        if (cartData[i].data[j].id == id) {
          return {
            i,
            j
          };
        }
      }
    }
  },

  // 获取所有已经勾选的id
  _getSelectedGoods() {
    var cartData = this.data.cartData,
      len = cartData.length,
      selectedIds = [];
    for (let i = 0; i < len; i++) {
      var childlen = cartData[i].data.length;
      for (let j = 0; j < childlen; j++) {
        if (cartData[i].data[j].selected == 1 && cartData[i].data[j].skusStatus.status != -1) {
          selectedIds.push(parseInt(cartData[i].data[j].id));
        }
      }
    }
    return selectedIds;
  },
  todisabled:function(){
    return
  },
  /*选择商品*/
  toggleSelect: function(event) {
    var id = cart.getDataSet(event, 'id'),
      status = cart.getDataSet(event, 'status'),
      shopIdx = this._getProductIndexById(id).i,
      index = this._getProductIndexById(id).j;
    if (this.data.cartData[shopIdx].data[index].selected == 1) {
      this.data.cartData[shopIdx].data[index].selected = 0;
    } else {
      this.data.cartData[shopIdx].data[index].selected = 1
    }
    this._resetCalculatorTotoltal();
  },

  _isShopSelected: function(cartData) {
    var len = cartData.length,
      shopCount = 0;
    this.data.hasGoodsSelected = false;
    for (let i = 0; i < len; i++) {
      var childLen = cartData[i].data.length;
      var flag = 1;
      for (let j = 0; j < childLen; j++) {
        if (cartData[i].data[j].selected == 0) {
          flag = 0;
        } else if (cartData[i].data[j].selected == 1) {
          this.data.hasGoodsSelected = true;
        }
      }
      cartData[i].shop.isShopSelectedAll = flag;
      if (cartData[i].shop.isShopSelectedAll == 1) {
        shopCount++
      }
    }
    this.setData({
      shopCount: shopCount
    })
    return cartData;
  },

  /*店铺全选*/
  toggleSelectShopAll: function(event) {
    var status = cart.getDataSet(event, 'status'),
      index = cart.getDataSet(event, 'index'),
      cartData = this.data.cartData[index],
      len = cartData.data.length,
      flag = 1;
    for (let j = 0; j < len; j++) {
      if (status == 1) {
        cartData.data[j].selected = 0;
      } else {
        cartData.data[j].selected = 1;
      }
    }
    this._resetCalculatorTotoltal();
  },

  /*全选*/
  toggleSelectAll: function(event) {
    var status = cart.getDataSet(event, 'status'),
      cartData = this.data.cartData,
      len = cartData.length;
    if (status == 'true') {
      for (let i = 0; i < len; i++) {
        var childLen = cartData[i].data.length;
        cartData[i].shop.isShopSelectedAll = 0;
        for (let j = 0; j < childLen; j++) {
          cartData[i].data[j].selected = 0;
        }
      }
    } else if (status == 'false') {
      for (var i = 0; i < len; i++) {
        var childLen = cartData[i].data.length;
        cartData[i].shop.isShopSelectedAll = 1;
        console.log(cartData[i].shop.isShopSelectedAll);
        for (var j = 0; j < childLen; j++) {
          cartData[i].data[j].selected = 1;

        }
      }
    }
    this.data.cartData = cartData;
    this._resetCalculatorTotoltal();
  },

  /*删除商品*/
  delete: function(event) {
    var id = cart.getDataSet(event, 'id'),
      index = this._getProductIndexById(id),
      that = this;
    cart.delete(id, (data) => {
      if (data.status == 1) {
        that._loadData();
        // this._resetCalculatorTotoltal();
      }
    });
  },

  /*跳转到商品详情*/
  onProductsItemTap: function(event) {
    var id = product.getDataSet(event, 'id');
    var skuid = product.getDataSet(event, 'skuid');

    wx.navigateTo({
      url: '../product/product?id=' + id + '&skuid=' + skuid
    })
  },

  /*提交订单*/
  submitOrder: function() {
    if (this.data.hasGoodsSelected) {
      wx.navigateTo({
        url: '../order/order?' + 'from=cart'
      });
    } else {
      wx.showToast({
        title: "请选择商品~",
        icon: 'none',
        duration: 2000
      })
    }
  },
  //自定义底部跳转
  footRedirect: function (e) {
    var url = e.currentTarget.dataset.url;
    wx.switchTab({
      url: url,
    })
  },
})